//
//  ZWUserInfoViewModel.swift
//  ZWWeibo
//
//  Created by flyiron on 16/4/19.
//  Copyright © 2016年 flyiron. All rights reserved.
//

import UIKit

class ZWUserInfoViewModel: NSObject {

    static let sharedViewModel:ZWUserInfoViewModel = ZWUserInfoViewModel()
    
   override init() {
        super.init()
        userModel = loadUserInfoInSanBox()
    }
    
    var userModel:ZWUserModel?
    
    var accessToken:String? {
        return userModel?.access_token
    }
    
    //判断是否登录
    var isLogin:Bool {
        if accessToken == nil {
            return false
        }
        
        guard let date = userModel?.expiresDate else{
            return false
        }
        if  NSDate().compare(date) == .OrderedAscending {
            return true
        }
        
        return false
    }
    
    
    func loadAccessToken(code:String,finished:(isSucessd:Bool)->()) {
        let url = "https://api.weibo.com/oauth2/access_token"
        let parmats = ["client_id":WB_APP_KEY,
            "client_secret":WB_APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_REDIRECT_URI]
        ZWNetworkTools.sharedTools.request(.Post, urlString: url, parameters: parmats) { (responseObject, error) -> () in
            if error != nil {
                print("网络错误\(error)")
                finished(isSucessd: false)

                return
            }
            
            //            print("请求成功\(responseObject)")
            if let dict = responseObject as? [String:AnyObject]{
                let userModel = ZWUserModel(dict: dict)
                //                print(userModel)
                self.getUserInfo(userModel,finished: finished)
                return
            }
            print("数据错误")
            finished(isSucessd: false)

            
        }
    }
  
    
    func getUserInfo(userModel: ZWUserModel,finished:(isSucessd:Bool)->()){
        let urlStr = "https://api.weibo.com/2/users/show.json"
        let paramets = ["access_token":userModel.access_token ?? "",
            "uid":userModel.uid ?? ""]
        ZWNetworkTools.sharedTools.request(urlString: urlStr, parameters: paramets) { (responseObject, error) -> () in
            if error != nil {
                print("网络错误\(error)")
                finished(isSucessd: false)

                return
            }
            //            print(responseObject)
            if let dict = responseObject as? [String: AnyObject]{
                userModel.name = dict["name"] as? String
                userModel.avatar_large = dict["avatar_large"] as? String
//                print(userModel)
                self.userModel = userModel
                //保存用户信息
                finished(isSucessd: true)
                self.saveUserInfo(userModel)
                return
            }
            print("数据错误")
            finished(isSucessd: false)
        }
    }
    
    func saveUserInfo(userModel:ZWUserModel){
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.data")
        //        print(path)
        NSKeyedArchiver.archiveRootObject(userModel, toFile: path)
    }
    
    //解档
    func loadUserInfoInSanBox() -> ZWUserModel?{
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.data")
    
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ZWUserModel
        return result
    }
    

}
